<template>
  <div>
    <el-dialog :visible.sync="dialog" title="菜单排序" width="80%">
      <div class="drag-box-card">
        <DragOrder :list.sync="sysMenus" @on-change="handleChange">
          <h4 slot="title">鼠标拖动以修改属性顺序</h4>
          <el-card class="drag-item" slot="content" slot-scope="content">
            <div style="margin-bottom: 10px; font-weight: bold;">排序：{{ content.index + 1 }}</div>
            <div>{{ content.item.metaTitle }}</div>
          </el-card>
        </DragOrder>
      </div>
      <span slot="footer">
        <el-button size="large" @click="dialog = false">取消</el-button>
        <el-button type="primary" size="large" @click="confirmOrder" :loading="loading">确认排序</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DragOrder from '@/components/DragOrder'
import { doPostJson } from '@/utils/utils'

export default {
  name: 'SysMenuOrderDialog',
  components: {
    DragOrder
  },
  data() {
    return {
      loading: false,
      dialog: false,
      parentId: null,
      sysMenus: []
    }
  },
  computed: {},
  mounted() {},
  methods: {
    initData(sysMenuId) {
      this.dialog = true
      this.parentId = sysMenuId
      this.sysMenus = []
      let params = {
        parentId: sysMenuId,
        sortColumn: 'menuOrder',
        isActive: 1,
        sortOrder: 'asc'
      }
      doPostJson('/sys-menu/admin/all-cond', params, {})
        .then(res => {
          if (res.data.rows.length > 0) {
            res.data.rows.forEach((row, index) => {
              this.sysMenus.push({
                id: row.id,
                metaTitle: row.metaTitle
              })
            })
          }
        })
        .catch(err => {})
    },
    handleChange({ src, target, oldIndex, newIndex }) {
      // this.handleList.push(`${src} => ${target}, ${oldIndex} => ${newIndex}`)
    },
    confirmOrder() {
      if (this.sysMenus.length === 0) {
        this.$message.warning('没有需要排序的菜单')
        return
      }
      // 保存菜单排序
      this.loading = true
      let params = []
      for (let i = 0, len = this.sysMenus.length; i < len; i++) {
        params.push({
          id: this.sysMenus[i].id,
          menuOrder: i + 1
        })
      }
      doPostJson('/sys-menu/admin/batch-update', params, {})
        .then(response => {
          this.loading = false
          this.$message.success('已更新菜单排序')
          this.dialog = false
        })
        .catch(error => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss">
.drag-box-card {
  display: inline-block;
  width: 100%;
  height: 100%;
  margin-top: 10px;
  .drag-item {
    margin: 5px;
  }
}
</style>
